package org.example.oop.thread;

/**
 * org.example.oop.thread
 *
 * @author moLei
 * @description 有100份礼品，两人同时发送，当剩下礼品小于10份时则不再送出
 *      利用多线程模拟该过程，并将线程名和礼物剩余数量打印出来
 * @date 2025/6/25
 */
public class GiftExercises {
    private static int giftCount = 100;

    public static void main(String[] args) {

        // 获取赠送礼物的对象
        GiftExercises giftExercises = new GiftExercises();

        // 创建线程进行赠送礼品
        new Thread(() -> {
            while (giftCount >= 10) {
                giftExercises.sendGift();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "小明").start();

        new Thread(() -> {
            while (giftCount >= 10) {
                giftExercises.sendGift();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "小王").start();

    }

    /**
     * 送出礼物
     */
    public synchronized void sendGift() {
        // 判断礼品的数量
        if (giftCount < 10) {
            System.out.println(Thread.currentThread().getName() + "-----当前礼品数量不足：" + giftCount);
            return;
        }
        System.out.println(Thread.currentThread().getName() + "送出了礼物，还剩" + --giftCount + "份礼品");
    }
}
